package k8s

import (
	"k8s-events-collector/config"
	"k8s-events-collector/pkg/es"
	"time"

	"go.uber.org/zap"
	coreV1 "k8s.io/api/core/v1"

	"k8s.io/client-go/kubernetes"
	v1 "k8s.io/client-go/kubernetes/typed/core/v1"
	"k8s.io/client-go/tools/clientcmd"
)

func GetKubeClient(kubeconfig string) (v1.EventInterface, error) {
	config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
	if err != nil {
		zap.L().Sugar().Fatalf("GetKubeClient.BuildConfigFromFlags: %s", err.Error())
		return nil, err
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		zap.L().Sugar().Fatalf("GetKubeClient.NewForConfig: %s", err.Error())
		return nil, err
	}
	return clientset.CoreV1().Events(coreV1.NamespaceAll), nil
}

func NewK8sEvents(event coreV1.Event) (e es.Events) {
	e.Cluster = config.C.Cluster.Name
	e.Namespace = event.InvolvedObject.Namespace
	e.Kind = event.InvolvedObject.Kind
	e.Name = event.InvolvedObject.Name
	e.Time = time.Now().Format(time.RFC3339)
	e.Type = event.Type
	e.Message = event.Message
	return
}
